1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
---
import { type CollectionEntry, getCollection, render } from 'astro:content';
import BlogPost from '../../layouts/BlogPost.astro';
import * as Gemtext from 'gemtext';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((post) => ({
params: { slug: post.id },
props: post,
}));
}
type Props = CollectionEntry<'blog'>;
function htmlEscape(str: string) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
const GemtextHTMLRenderer: Gemtext.Renderer<string> = {
preamble: function (): string {
return '';
},
postamble: function (): string {
return '';
},
text: function (content: string): string {
content = content.trim();
if (content === '') {
return '';
}
return `<p>${htmlEscape(content)}</p>`
},
link: function (url: string, alt: string): string {
url = url.replaceAll(/^\/images\//g, '/images/capsule/');
const imgExtensions: (string | undefined)[] = ['webp', 'png', 'svg', 'gif', 'jpg', 'jpeg', 'apng']
if (imgExtensions.includes(url.split('.').at(-1)?.toLowerCase())) {
return `<img src="${url}" alt="${alt}" />`;
}
return `<p>=> <a href="${url}">${alt}</a></p>`;
},
preformatted: function (content: string[], alt: string): string {
return `<pre alt="${alt}">${htmlEscape(content.join('\n'))}</pre>`
},
heading: function (level: number, text: string): string {
return `<h${level}>${htmlEscape(text)}</h${level}>`;
},
unorderedList: function (content: string[]): string {
return `<ul>${content.map(li=>`<li>${htmlEscape(li)}</li>`).join('')}</ul>`;
},
quote: function (content: string): string {
return `<blockquote>${htmlEscape(content)}</blockquote>`;
}
};
function postProcessGemtextToHtml(html: string): string {
html = mergeAdjacentBlockquotes(html);
return html;
}
function mergeAdjacentBlockquotes(html: string): string {
return html.replaceAll(/\<\/blockquote\>\<blockquote\>/gm, '<br>');
}
const post = Astro.props;
const Content = post.filePath?.endsWith('.gmi')
? postProcessGemtextToHtml(Gemtext.parse((post.body ?? '').replace(`# ${post.data.title}`, '')).generate(GemtextHTMLRenderer))
: (await render(post)).Content;
---
<BlogPost
title={post.data.title}
description={post.data.description}
pubDate={post.data.pubDate ?? new Date(post.id)}
updatedDate={post.data.updatedDate}
>
{ post.filePath?.endsWith('.gmi') ? <Fragment set:html={Content}></Fragment> : <Content />}
</BlogPost>
|